package com.cunshe.web;

import com.cunshe.common.*;
import com.cunshe.domain.*;
import com.cunshe.entity.vo.CorporateCultureVO;
import com.cunshe.service.*;
import com.cunshe.service.ProductFeatureService;
import com.google.common.reflect.TypeToken;
import com.sunkee.commons.utils.DateUtils;
import com.sunkee.commons.utils.ListUtils;
import com.sunkee.commons.utils.StringUtils;
import com.sunkee.entity.page.Pageable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Type;
import java.util.*;

@Controller
@RequestMapping("/")
public class HomeController extends BaseController{

    @Autowired
    private CooperativeCustomersService cooperativeCustomersService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private CompanyProfileService companyProfileService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private ProductService productService;
    @Autowired
    private MessageBoardService messageBoardService;
    @Autowired
    private BannerService bannerService;
    @Autowired
    private MemorabiliaService memorabiliaService;
    @Autowired
    private ProductFeatureService productFeatureService;
    @Autowired
    private CaseService caseService;

    @ModelAttribute
    public void loadMenu(Model model) {
        List<Menu> menus = menuService.all();
        menus = (List<Menu>) ListUtils.list2Tree(menus);

        CompanyProfile companyProfile = companyProfileService.get();
        int i = DateUtils.differentDays(companyProfile.getEstablishDate(), new Date());
        int year = 1;
        if(i > 1){
            year = i / 365;
        }

        String lang = Optional.ofNullable(request.getSession().getAttribute("lang"))
                .map(Object::toString)
                .orElse(LangEnum.zh.name());
        Map<String, String> i18n = I18n.getI18n(lang);

        model.addAttribute("i18n", i18n);

        model.addAttribute("companyProfile", companyProfile);
        model.addAttribute("year", year);
        model.addAttribute("page", "");
        model.addAttribute("menus", menus);
    }

    /**
     * 首页
     */
    @GetMapping("")
    public String index(Model model) {
        Banner banner = bannerService.get(1);
        // 合作客户
        List<CooperativeCustomers> coperativeCustomers = cooperativeCustomersService.all();
        List<News> news = newsService.top(6, 1);

        List<Product> productList = productService.list(Product.builder().recommend(true).build());

        model.addAttribute("productList", productList);
        model.addAttribute("news", news);
        model.addAttribute("banner", banner);
        model.addAttribute("coperativeCustomers", coperativeCustomers);
        model.addAttribute("page", "home");
        return "index";
    }

    @GetMapping(value = "about_us")
    public String about_us(Model model){
        CompanyProfile companyProfile = (CompanyProfile) model.getAttribute("companyProfile");
        List<CorporateCultureVO> corporateCultureList = null;

        if(StringUtils.isNotBlank(companyProfile.getCorporateCulture())) {
            Type type = new TypeToken<List<CorporateCultureVO>>() {}.getType();
            corporateCultureList = gson.fromJson(companyProfile.getCorporateCulture(), type);
        }

        Long id = 5L;
        List<Menu> menus = menuService.all();
        Menu menu = menus.stream()
                .filter(var -> var.getId().equals(id))
                .findFirst()
                .orElse(null);

        //
        List<Memorabilia> memorabiliaList = memorabiliaService.get(1);
        model.addAttribute("menu", menu);
        model.addAttribute("memorabiliaList", memorabiliaList);
        model.addAttribute("corporateCultureList", corporateCultureList);
        return "about-us";
    }

    /**
     * 合作客户
     */
    @GetMapping(value = "client")
    public String client(Model model) {
        Long id = 6L;
        List<Menu> menus = menuService.all();
        Menu menu = menus.stream()
                .filter(var -> var.getId().equals(id))
                .findFirst()
                .orElse(null);

        List<CooperativeCustomers> all = cooperativeCustomersService.all();

        model.addAttribute("coperativeCustomers", all);
        model.addAttribute("menu", menu);
        return "client";
    }

    @GetMapping(value = "product")
    public String product(Model model){
        List<Menu> menusList = (List<Menu>) model.getAttribute("menus");
        Menu menu = menusList.stream()
                .filter(var -> var.getId() == 2)
                .findFirst()
                .orElse(null);

        model.addAttribute("menu", menu);
        return "product";
    }

    @GetMapping(value = "visual")
    public String visual(Model model){
        long id = 3;
        List<Menu> menusList = (List<Menu>) model.getAttribute("menus");
        Menu menu = menusList.stream()
                .filter(var -> var.getId() == id)
                .findFirst()
                .orElse(null);

        model.addAttribute("menu", menu);
        return "visual";
    }

    @GetMapping(value = "visual_case")
    public String visual_case(@RequestParam("id") Long id, Model model){
        List<Menu> menus = menuService.all();
        Menu menu = menus.stream()
                .filter(var -> var.getId().equals(id))
                .findFirst()
                .orElse(null);

        List<TestCase> testCase = caseService.getByMenuId(id);

        model.addAttribute("testCase", testCase);
        model.addAttribute("menu", menu);
        return "visual-case";
    }

    @GetMapping(value = "visual_inspection")
    public String visual_inspection(@RequestParam("id") Long id, Model model){
        List<Menu> menus = menuService.all();
        Menu menu = menus.stream()
                .filter(var -> var.getId().equals(id))
                .findFirst()
                .orElse(null);
        // 产品特点
        List<ProductFeature> productFeatureList = productFeatureService.getByMenuId(id, true);

        //案例
        List<TestCase> testCase = caseService.getByMenuId(id);

        model.addAttribute("testCase", testCase);
        model.addAttribute("productFeatureList", productFeatureList);
        model.addAttribute("menu", menu);
        return "visual-inspection";
    }

    @GetMapping(value = "case_detail")
    public String case_detail(@RequestParam("id") Long id, Model model){
        List<Menu> menus = menuService.all();
        Menu menu = menus.stream()
                .filter(var -> var.getId().equals(id))
                .findFirst()
                .orElse(null);

        //案例
        TestCase testCase = caseService.get(id);

        model.addAttribute("testCase", testCase);
        model.addAttribute("menu", menu);
        return "case-detail";
    }

    @GetMapping(value = "automation")
    public String automation(Model model){
        long id = 4;
        List<Menu> menus = (List<Menu>) model.getAttribute("menus");
        Menu menu = menus.stream()
                .filter(var -> var.getId() == id)
                .findFirst()
                .orElse(null);

        List<ProductFeature> productFeatureList = productFeatureService.getByMenuId(id, true);

        model.addAttribute("productFeatureList", productFeatureList);
        model.addAttribute("menu", menu);
        return "automation";
    }

    /**
     *
     */
    @GetMapping(value = "join_us")
    public String join_us(Model model) {
        Long id = 8L;
        List<Menu> menus = (List<Menu>) model.getAttribute("menus");
        Menu menu = menus.stream()
                .filter(var -> var.getId().equals(id))
                .findFirst()
                .orElse(null);

        model.addAttribute("menu", menu);
        return "join-us";
    }

    @GetMapping(value = "recruit")
    public String recruit(@RequestParam("id") Long id, @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, Model model) {
        List<Menu> menus = menuService.all();
        Menu menu = menus.stream()
                .filter(var -> var.getId().equals(id))
                .findFirst()
                .orElse(null);

        Pageable<News> pagelist = newsService.pagelist(pageNo, 6, News.builder().type(4).build());
        List<News> news = pagelist.getResult();
        int end = news.size() / 2;
        if(end % 2 != 0){
            end++;
        }

        model.addAttribute("end", end);
        model.addAttribute("news", news);
        model.addAttribute("pageNo", pageNo);
        model.addAttribute("pageSize", pagelist.getCount());
        model.addAttribute("menu", menu);
        return "recruit";
    }

    @GetMapping(value = "recruit_detail")
    public String recruit_detail(@RequestParam("id") Long id, Model model) {
        News news = newsService.get(id);
        model.addAttribute("news", news);
        return "recruit-detail";
    }

    /**
     * 联系我们
     */
    @GetMapping(value = "contact_us")
    public String contact_us(@RequestParam("id") Long id, Model model) {
        List<Menu> menus = menuService.all();
        Menu menu = menus.stream()
                .filter(var -> var.getId().equals(id))
                .findFirst()
                .orElse(null);

        model.addAttribute("menu", menu);
        return "contact-us";
    }

    /**
     * 新闻
     */
    @GetMapping(value = {"news", "new_list"})
    public String news(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, Model model) {
        Long id = 7L;
        List<Menu> menus = menuService.all();
        Menu menu = menus.stream()
                .filter(var -> var.getId().equals(id))
                .findFirst()
                .orElse(null);

        Pageable<News> pagelist = newsService.pagelist(pageNo, 3, News.builder().type(1).build());
        List<News> news = pagelist.getResult();

        model.addAttribute("menu", menu);
        model.addAttribute("news", news);
        model.addAttribute("pageNo", pageNo);
        model.addAttribute("pageSize", pagelist.getCount());
        return "new-list";
    }

    /**
     * 新闻详情
     */
    @GetMapping(value = "new_detail")
    public String new_detail(@RequestParam(value = "id") Long id, Model model) {
        News news = newsService.get(id);

        model.addAttribute("news", news);
        return "new-detail";
    }

    /**
     * 切换语言
     * @param lang
     * @param request
     * @return
     */
    @GetMapping(value = "setLanguage")
    @ResponseBody
    public ResponseVO lang(@RequestParam("lang") LangEnum lang, HttpServletRequest request){
        System.out.println(lang);
        request.getSession().setAttribute("lang", lang.name());
        return ResponseVO.success();
    }

    /**
     * 保存
     * @param messageBoard
     * @return
     */
    @PostMapping(value = "saveMessage")
    @ResponseBody
    public ResponseVO saveMessage(HttpServletRequest request, MessageBoard messageBoard) {
        HttpSession session = request.getSession();
        String saveMessage = (String) session.getAttribute("saveMessage");
        String remoteHost = request.getRemoteHost();

        if(remoteHost.equals(saveMessage)) {
            return ResponseVO.success(0, "留言成功!");
        }

        messageBoardService.insert(messageBoard);
        session.setAttribute("saveMessage", remoteHost);
        return ResponseVO.success(0, "留言成功。");
    }

    @GetMapping(value = "parallel_robot")
    public String parallel_robot(@RequestParam("id") Long id, Model model){
        List<Menu> menus = menuService.all();
        Menu menu = menus.stream()
                .filter(var -> var.getId().equals(id))
                .findFirst()
                .orElse(null);

        // 产品特点
        List<ProductFeature> productFeatureList = productFeatureService.getByMenuId(id, true);

        // 产品列表
        List<Product> productList = productService.getByCategory(String.valueOf(id));

        model.addAttribute("productList", productList);
        model.addAttribute("productFeatureList", productFeatureList);
        model.addAttribute("menu", menu);
        return "parallel-robot";
    }

    @GetMapping(value = "product_detail")
    public String product_detail(@RequestParam("id") Long id, Model model){
        Product product = productService.get(id);


        model.addAttribute("product", product);
        return "product-detail";
    }

    @GetMapping(value = "chronicle_detail")
    public String chronicle_detail(@RequestParam("id") Long id, Model model){
        Memorabilia memorabilia = memorabiliaService.get(id);
        if(memorabilia == null) {
            return null;
        }
        List<Memorabilia> memorabiliaList = memorabiliaService.get2(2, memorabilia.getMdate());

        model.addAttribute("memorabilia", memorabilia);
        model.addAttribute("memorabiliaList", memorabiliaList);
        return "chronicle-detail";
    }

}
